package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.mapper.UserInfoMapper;
import com.tanhua.model.domain.UserInfo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService
public class UserInfoApiImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void save(UserInfo userInfo) {
        userInfo.setCreated(new Date()); //创建时间
        userInfo.setUpdated(new Date()); //更新时间
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        userInfo.setUpdated(new Date());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public UserInfo findById(Long userId) {
        return userInfoMapper.selectById(userId);
    }

    //根据用户id集合查询用户详情
    public Map<Long, UserInfo> findByIds(List<Long> userIds,UserInfo params) {
        //select * from tb_user_info where id in (1,2,3,4,5)   and age<20 and gender = ''
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",userIds);
        if(params != null) {
            if(params.getAge() != null) {
                queryWrapper.lt("age",params.getAge());
            }
            if(params.getGender() != null) {
                queryWrapper.eq("gender",params.getGender());
            }
        }

        List<UserInfo> userInfos = userInfoMapper.selectList(queryWrapper);
        //将list集合转化为Map集合
        Map<Long, UserInfo> map = new HashMap<>();
        for (UserInfo userInfo : userInfos) {
            map.put(userInfo.getId(),userInfo);
        }
        return map;
    }

    //分页查询
    public IPage<UserInfo> findAll(int page, int pagesize) {
        Page<UserInfo> params = new Page<>(page,pagesize); //分页参数
        return userInfoMapper.selectPage(params,null);
    }


}
